package com.atguigui.leetcode;

/**
 * 640.求解方程
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/8/10 9:04
 */
public class P640SolveTheEquation {
    public static void main(String[] args) {
        Solution solution = new P640SolveTheEquation().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String solveEquation(String equation) {
            //factor：x变量前的系数        val：数值
            int factor = 0, val = 0;
            int index = 0, n = equation.length(), sign1 = 1; // 等式左边默认系数为正
            while (index < n) {
                //等式右边
                if (equation.charAt(index) == '=') {
                    sign1 = -1; // 等式右边默认系数为负
                    index++;
                    continue;
                }

                //sign2为当前数值的系数
                int sign2 = sign1, number = 0;
                boolean valid = false; // 记录 number 是否有效
                //数字前的符号转化，将等号右边的数字前面加上负号后移到左边进行相加，如果等号右边的数是负，则取反
                if (equation.charAt(index) == '-' || equation.charAt(index) == '+') { // 去掉前面的符号
                    sign2 = (equation.charAt(index) == '-') ? -sign1 : sign1;
                    index++;
                }
                //判断是否为数字
                while (index < n && Character.isDigit(equation.charAt(index))) {
                    number = number * 10 + (equation.charAt(index) - '0');
                    index++;
                    valid = true;
                }

                //获取x变量前的系数
                if (index < n && equation.charAt(index) == 'x') { // 变量
                    //如果valid为数字则系数*数值，如果不为数字则加系数
                    factor += valid ? sign2 * number : sign2;
                    index++;
                } else { // 数值
                    //系数乘以数值
                    val += sign2 * number;
                }
            }

            if (factor == 0) {
                return val == 0 ? "Infinite solutions" : "No solution";
            }
            if (val % factor != 0) {
                return "No solution";
            }
            return "x=" + (-val / factor);
        }
    }
}
